<?php
include("../validar.php");
include("../config.php");
$USER=$_SESSION['usuario'];
$ELID=$_SESSION['id'];

if($cierre){
	$queryExisteReg=pg_fetch_array(pg_query("SELECT * FROM caja WHERE idsucursal=$lstSucursal AND numero_caja=$lstNumeroCaja AND estado='ABIERTO'"));
	$Qsuc=pg_query("SELECT * FROM sucursales WHERE idsucursal=$lstSucursal");
	$regSuc=pg_fetch_array($Qsuc);
	if($queryExisteReg > 0){
		$abre=pg_query("UPDATE caja SET fecha_cierre='$txtFecha', monto_cierre='$txtCierre', estado='CERRADO' WHERE idcaja='$queryExisteReg[idcaja]' AND numero_caja=$lstNumeroCaja AND idsucursal=$lstSucursal"); 
		echo "
		<script>
			alert('LA CAJA DE LA SUCURSAL: ".strtoupper($regSuc[nombre])." SE CERRO CORRECTAMENTE.');
			location.href='?informe=$queryExisteReg[idcaja]';
		</script>";
	}else{
		echo "<script>alert('LA CAJA YA SE ENCUENTRA CERRADA EN LA SUCURSAL: ".strtoupper($regSuc[nombre])." Y CAJA: $lstNumeroCaja')</script>";
	}
}
?>
<script>
document.focus();
function centrar(){
	try{
		a=(screen.width-document.body.clientWidth) / 2;
		b=(screen.height-document.body.clientHeight) / 2; 
		moveTo(a,b); 
	}catch(e){
		alert("Error en funcion calculoTotal: "+e);
	}
}

function cerrar(){
	try{
		location.href='?caja=cerrar';
	}catch(e){
		alert('Error en funcion cerrar(): '+e);
	}
}

function funcionSend(){
	sucursal=document.getElementById('lstSucursal').value;
	caja=document.getElementById('lstNumeroCaja').value;
	if(sucursal!="" && caja!=""){
		location.href='?suc='+sucursal+'&caja='+caja
	}
}
</script>
<style type="text/css">
<!--
body {
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
}
.GRANDE {
	font-size: 18px;
	font-weight: bold;
}
.MASGRANDE {
	font-size: 22px;
	font-weight: bold;
}
.loc6 {
	font-size: 14px;
	font-weight: bold;
	color: #000000;
	font-family: Verdana, Arial, Helvetica, sans-serif;
}
.Estilo1 {
	font-size: 12px;
	font-weight: bold;
}
body,td,th {
	font-family: Arial, Helvetica, sans-serif;
}
-->
</style>
<title>CIERRE & ARQUEO DE CAJA</title>
<body bgcolor="#EFEFEF" onLoad="centrar();">
<? if(!$informe){?>
<table width="425" border="0" align="center" cellpadding="0" cellspacing="2">
  <tr>
    <td><fieldset style="background-color:#FFFFFF">
      <legend><strong>CIERRE DE CAJA </strong></legend>
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><form name="form">
              <table width="425" border="0" align="center" cellpadding="0" cellspacing="2">
                <tr>
                  <td><span class="loc6">SUCURSAL</span></td>
                  <td><select name="lstSucursal" id="lstSucursal" style="font-size:23px; color:#FF0000" onChange="funcionSend()">
                      <option value="0" ></option>
                      <? $query=pg_query("SELECT * FROM sucursales")?>
                      <? while($rs=pg_fetch_array($query)){?>
                      <option value="<?=$rs[idsucursal]?>" <? if($rs[idsucursal]==$suc){?>selected="selected"<? }?>>
                      <?=$rs[nombre]?>
                      </option>
                      <? }?>
                    </select></td>
                </tr>
                <tr>
                  <td class="loc6">N&deg; CAJA</td>
                  <td><select name="lstNumeroCaja" id="lstNumeroCaja" style="font-size:19px; color:#FF0000" onChange="funcionSend()" >
                      <option value=""></option>
                      <? 
			$rs=1;
			while($rs<=$GLOBAL_NUM_CAJAS){?>
                      <option value="<?=$rs?>" <? if($rs==$caja){?>selected="selected"<? }?>> Caja N&deg;
                      <?=$rs?>
                      </option>
                      <? $rs++; }?>
                    </select></td>
                </tr>
                <tr>
                  <td class="loc6">FECHA CIERRE </td>
                  <td><input name="txtFecha" type="text" id="txtFecha" style="font-size:23px; color:#FF0000" value="<?=date("Y-m-d")?>" size="22" /></td>
                </tr>
                <tr>
                  <td width="213"><span class="loc6">MONTO CIERRE </span></td>
                  <td width="192"><?
				/*VERIFICAMOS SI ESTA ABIERTA*/
				$existeCaja="";
				if($_GET['caja']){
					$queryCajaAbierta=pg_query("SELECT idcaja FROM caja WHERE idsucursal=$suc AND numero_caja=$caja AND estado='ABIERTO'");
					$rsetCaja=pg_num_rows($queryCajaAbierta);
					if($rsetCaja>0){
						$existeCaja=1;
					}else{
						$existeCaja=0;
					}
				}
				/*VERIFICAMOS TOTAL*/
				$queryTotal=pg_query("SELECT round(sum(venta.total)+caja.monto_apertura) as total 
									  FROM venta, caja
									  WHERE venta.idcaja=caja.idcaja
									  AND venta.idestadoventa=(SELECT idestadoventa FROM estadoventa WHERE descripcion='TERMINADO')
									  AND venta.idsucursal=$suc
									  AND venta.idcaja=(SELECT idcaja FROM caja WHERE idsucursal=$suc AND numero_caja=$caja AND estado='ABIERTO')
									  GROUP BY caja.monto_apertura");
				$regSum=pg_fetch_array($queryTotal);
				$totalCajas=pg_num_rows($queryTotal);
				$total=round($regSum[total]);
			  ?>
                    <? if($_GET[caja] && $existeCaja==0){?>
                    <span style="font-size:10px; color:#990000">LA CAJA Y SUCURSAL NO ESTA ABIERTA</span>
                    <? }?>
                    <input name="txtCierre" type="text" id="txtCierre" style="font-size:23px; color:#FF0000" size="22" value="<?=$total?>" /></td>
                </tr>
              </table>
              <table width="425" border="0" align="center" cellpadding="0" cellspacing="0">
                <tr>
                  <td colspan="2"><hr></td>
                </tr>
                <tr>
                  <td><input type="button" name="Submit" value="Refrescar" onClick="location.href='?'"></td>
                  <td align="right"><input name="quijote" type="hidden" id="quijote" value="ok">
                    <? if($_GET[caja] && $existeCaja==1){?>
                    <input type="submit" name="cierre" id="cierre" value="CERRAR CAJA &raquo;" style="font-size:12px; font-weight:bold" onClick="finalizar(<?=$monto?>,<?=$facturaNumero?>,<?=$iva5?>,<?=$iva10?>,'cerrado')" />
                    <? }?>
                  </td>
                </tr>
              </table>
            </form></td>
        </tr>
      </table>
      </fieldset></td>
  </tr>
</table>
<br>
<fieldset style="background-color:#FFFFFF">
<legend><strong>LISTA DE CAJAS (ABIERTOS Y CERRADOS) </strong></legend>
<table width="100%" border="0" align="center" cellpadding="5" cellspacing="0">
  <tr>
    <td><table width="100%" border="0" cellspacing="0" cellpadding="3" style="border:1px #000000 solid">
        <tr>
          <td width="20%" bgcolor="#EFEFEF"><span class="Estilo1">NOMBRE DE <br>
            SUCURSAL</span></td>
          <td width="20%" bgcolor="#EFEFEF"><span class="Estilo1">FECHA <br>
            APERTUDA </span></td>
          <td width="20%" bgcolor="#EFEFEF"><span class="Estilo1">MONTO <br>
            APERTURA </span></td>
          <td width="14%" bgcolor="#EFEFEF"><span class="Estilo1">FECHA <br>
            CIERRE </span></td>
          <td width="16%" bgcolor="#EFEFEF"><span class="Estilo1">MONTO <br>
            CIERRE </span></td>
          <td width="10%" bgcolor="#EFEFEF"><span class="Estilo1">ESTADO <br>
            CAJA </span></td>
          <td width="10%" bgcolor="#EFEFEF"><span class="Estilo1">RE-IMPRIMIR</span></td>
        </tr>
        <? 
	  //AND c.fecha_apertura='$hoy' AND c.estado='ABIERTO'
	  $hoy=date("Y-m-d");
	  $queryCajas=pg_query("SELECT c.*, s.nombre FROM caja AS c, sucursales AS s WHERE c.idsucursal=s.idsucursal ORDER BY c.idcaja DESC LIMIT 15 OFFSET 0");
	  while($reg=pg_fetch_array($queryCajas)){
		$queryTotal=pg_query("SELECT sum(total) as total FROM venta WHERE idsucursal=$reg[idsucursal] AND idcaja=$reg[idcaja]");
		$regSum=pg_fetch_array($queryTotal);
		$total=number_format((int)$regSum[total], 0, '','.');
	  ?>
        <tr>
          <td height="30" nowrap style="border-top:1px #333333 solid"><?=$reg['nombre']?></td>
          <td nowrap style="border-top:1px #333333 solid"><?=$reg[fecha_apertura]?></td>
          <td nowrap style="border-top:1px #333333 solid"><?=number_format(round($reg[monto_apertura]),0,'','.')?>
            Gs.</td>
          <td nowrap style="border-top:1px #333333 solid"><?=$reg[fecha_cierre]?></td>
          <td nowrap style="border-top:1px #333333 solid"><b>
            <?=number_format(round($reg[monto_cierre]),0,'','.')?>
            Gs.</b> </td>
          <td nowrap style="border-top:1px #333333 solid"><?=$reg[estado]?></td>
          <td align="center" nowrap style="border-top:1px #333333 solid"><? if($reg[estado]=="CERRADO"){?>
            <a href="?informe=<?=$reg[idcaja]?>" style="font-size:12px; font-weight:bold; text-decoration:none; color:#006600">[RE-IMPRIMIR]</a>
            <!--
			<form name="form1" method="post" action="">
                <input name="informe" type="hidden" id="informe" value="<?=$reg[idcaja]?>">
                <input name="reimprimir" type="submit" id="reimprimir" value="Reimprimir">
            </form>
			-->
            <? }else{?>
            <span style="font-size:12px; font-weight:bold; text-decoration:none; color:#990000">[DEBE CERRAR]</span>
            <? }?>          </td>
        </tr>
        <? }?>
      </table></td>
  </tr>
</table>
<? }else{?>
<?
/*CONSULTA VENTAS*/
$queryVentas=pg_query("SELECT sum(total) total, sum(iva10) iva10, sum(iva5), sum(total_descuento) descuentos FROM venta WHERE idcaja=$informe AND idestadoventa!=3 ");
$reg=pg_fetch_array($queryVentas);

/*CONSULTA METODOS*/
$queryMetodos=pg_query("SELECT sum(cv.monto)
FROM venta v, cobrosventa cv, metodospago mp
WHERE cv.idventa=v.idventa
AND cv.idmetodospago=mp.idmetodospago
AND v.idestadoventa=(SELECT idestadoventa FROM estadoventa WHERE descripcion='TERMINADO') 
AND v.idsucursal=1 
AND v.idcaja=$informe
AND mp.nombre like '%Tarjeta%'");
$regMetodo=pg_fetch_array($queryMetodos);

/*CONSULTA METODOS*/
$queryMetodosC=pg_query("SELECT sum(cv.monto)
FROM venta v, cobrosventa cv, metodospago mp
WHERE cv.idventa=v.idventa
AND cv.idmetodospago=mp.idmetodospago
AND v.idestadoventa=(SELECT idestadoventa FROM estadoventa WHERE descripcion='TERMINADO') 
AND v.idsucursal=1 
AND v.idcaja=$informe
AND mp.nombre like '%Cheque%'");
$regMetodoCheque=pg_fetch_array($queryMetodosC);

/*CONSULTA NOTA CREDITO*/
$queryNota=pg_query("SELECT sum(cv.monto)
FROM venta v, cobrosventa cv, metodospago mp
WHERE cv.idventa=v.idventa
AND cv.idmetodospago=mp.idmetodospago
AND v.idestadoventa=(SELECT idestadoventa FROM estadoventa WHERE descripcion='TERMINADO') 
AND v.idsucursal=1 
AND v.idcaja=$informe
AND UPPER(mp.nombre) like UPPER('%NOTA%')");
$regMetodoNota=pg_fetch_array($queryNota);

/*CONSULTA CAJA*/
$queryCaja=pg_query("SELECT * FROM caja WHERE idcaja=$informe");
$regCaja=pg_fetch_array($queryCaja);
?>
<script>
function imprime(){
	document.getElementById('imprimir').style.visibility='hidden';
	document.getElementById('imprimir').style.display='none';
	window.print();
}
</script>
<table width="460" border="0" align="center" cellpadding="0" cellspacing="0" style="font-family:monospace; font-size:18px">
  <tr>
    <td align="center">CENTRO COMERCIAL LUQUE&Ntilde;O </td>
  </tr>
  <tr>
    <td align="center">INFORME | FECHA
      <?=date("Y-m-d")?></td>
  </tr>
  <tr>
    <td><hr></td>
  </tr>
  <tr>
    <td align="center">CIERRE DE FECHA
      <?=$regCaja[fecha_cierre]?></td>
  </tr>
  <tr>
    <td><hr></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" cellspacing="0" cellpadding="3" style="font-size:18px">
        <tr>
          <td width="51%">Total Venta</td>
          <td width="49%"><?=number_format($reg[total]+$reg[descuentos], 0, '','.')?>
            Gs.</td>
        </tr>
        <tr>
          <td>Total Descuento</td>
          <td><?=number_format(round($reg[descuentos]), 0, '','.')?>
            Gs.</td>
        </tr>
        <tr style="border-top:1px #000 solid">
          <td><strong>Total Facturado</strong></td>
          <td><strong>
            <?=number_format($reg[total], 0, '','.')?>
            Gs.</strong></td>
        </tr>
        <tr>
          <td colspan="2">..................................</td>
        </tr>
        <tr>
          <td>Total Tarjeta</td>
          <td><?=number_format($regMetodo[0], 0, '','.')?>
            Gs.</td>
        </tr>
        <tr>
          <td>Total Cheque</td>
          <td><?=number_format($regMetodoCheque[0], 0, '','.')?>
            Gs.</td>
        </tr>
        <tr>
          <td>Total Nota Credito </td>
          <td><?=number_format($regMetodoNota[0], 0, '','.')?> Gs.</td>
        </tr>
        <tr>
          <td colspan="2">..................................</td>
        </tr>
        <tr>
          <td>Total IVA 10%</td>
          <td><?=number_format($reg[iva10], 0, '','.')?>
            Gs.</td>
        </tr>
        <tr>
          <td>Total IVA 5%</td>
          <td><?=number_format($reg[iva5], 0, '','.')?>
            Gs.</td>
        </tr>
        <tr>
          <td colspan="2">..................................</td>
        </tr>
        <tr>
          <td>Factura Inicial</td>
          <td><?=number_format($regCaja[numero_factura_inicial], 0, '','.')?></td>
        </tr>
        <tr>
          <td>Factura Final</td>
          <td>
		  <? 
		  
		  ?>
		  <?=number_format($regCaja[numero_factura] - 1, 0, '','.')?></td>
        </tr>
      </table></td>
  </tr>
</table>
<br>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="imprimir">
  <tr>
    <td align="center"><input type="button" name="button" id="button" value="Cerrar" onClick="window.close()">
      <input type="button" name="Imprimir" id="Imprimir" value="Imprimir" onClick="imprime()">
      <input type="button" name="Submit2" value="Volver" onClick="location.href='?'">
    </td>
  </tr>
</table>
</fieldset>
<? }?>
        